#include "Reader.h"
#include <QFuture>
#include <QMutexLocker>
#include <QDebug>

QMutex Reader::mutex(QMutex::NonRecursive);

Reader::Reader(Library *library, int readingTime, QObject *parent) :
	QThread(parent), library(library), readingTime(readingTime)
{
}

void Reader::run()
{
	while (true) {
		int book = tryToGetBook();
		if (book != -1) {
			readBook();
			returnBook(book);
		}
	}
}

void Reader::readBook()
{
//	qDebug() << "Reader::readBook";
	msleep(readingTime);
}

int Reader::tryToGetBook()
{
	QMutexLocker locker(&mutex);
	int freeBooksNumber = library->getFreeBooksNumber();
	if (freeBooksNumber != 0) {
		return library->getAnyBook();
	} else {
		return -1;
	}
}

void Reader::returnBook(int bookId)
{
//	qDebug() << "Reader::returnBook " << bookId;
	library->returnBook(bookId);
}

